/* 用户注册 */
const router = require("koa-router")();
import { ReadFile, WriteFile } from "../utils/ReadWriteFile";
import { createId } from "../utils/createId";
function getCurrentFormattedTime() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0"); // 月份是从0开始的，所以要加1
  const day = String(now.getDate()).padStart(2, "0");
  const hours = String(now.getHours()).padStart(2, "0");
  const minutes = String(now.getMinutes()).padStart(2, "0");
  const seconds = String(now.getSeconds()).padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
/* 查询所有的普通用户*/
router.post("/api/addAnnouncement", async (ctx) => {
  const { username, password, type, title, content, Announcement } =
    ctx.request.body;
  let trafficResult = await ReadFile(type);
  const res = trafficResult.find((item) => item.username == username);
  let announcenmentResult = await ReadFile(Announcement);
  let id = createId();
  if (username) {
    if (title && content) {
      let Announcementobj = {
        id,
        time: getCurrentFormattedTime(),
        title,
        content,
        publisher: username,
        type,
      };
      announcenmentResult.unshift(Announcementobj);
      WriteFile({
        type: Announcement,
        result:announcenmentResult,
      });
      let res1 = trafficResult.filter((item) => item.username != username);
      let newAnnounce =           {
        id,
        time: getCurrentFormattedTime(),
        title,
        content,
      }
      res.announcenment.push(newAnnounce)
      var obj = {
        id: createId(),
        username,
        password,
        type,
        interestPoints: res.interestPoints,
        announcenment: res.announcenment,
        isOnline: true,
      };
      res1.push(obj);
      WriteFile({
        type,
        result: res1,
      });
      ctx.body = {
        code: 200,
        msg: "发布成功",
        obj,
        Announcementobj

      };
    } else {
      ctx.body = {
        code: 400,
        msg: "请输入有效内容",
      };
    }
  } else {
    ctx.body = {
      code: 400,
      msg: "请先登录",
    };
  }
});
module.exports = router;
